package cn.xiaopengstack.trigger.listener;

import cn.xiaopengstack.domain.activity.model.entity.RechangeTradeResultEntity;
import cn.xiaopengstack.domain.activity.model.valobj.OrderStateVO;
import cn.xiaopengstack.domain.activity.repository.IRaffleActivityRepository;
import cn.xiaopengstack.domain.credit.even.CreateAdjustSuccessEvent;
import cn.xiaopengstack.types.event.BaseEvent;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author jiangyangang
 */
@RocketMQMessageListener(
        topic = "send_credit_adjust_success_topic",
        consumerGroup = "jyg-big-marketing-group",
        selectorType = SelectorType.TAG,
        selectorExpression = "*"
)
@Component
@Slf4j
public class CreditAdjustSuccessConsumer implements RocketMQListener<String> {

    @Resource
    private IRaffleActivityRepository raffleActivityRepository;

    @Override
    public void onMessage(String messageStr) {
        BaseEvent.EventMessage<CreateAdjustSuccessEvent.CreateAdjustSuccessEventMessage> evenMessage = JSONObject.parseObject(messageStr, new TypeReference<BaseEvent.EventMessage<CreateAdjustSuccessEvent.CreateAdjustSuccessEventMessage>>() {
        });

        CreateAdjustSuccessEvent.CreateAdjustSuccessEventMessage message = evenMessage.getMessage();
        switch (message.getTradeNameVO()) {
            case CONVERT_SKU:
                RechangeTradeResultEntity rechangeTradeResult = RechangeTradeResultEntity.builder()
                        .orderStateVO(OrderStateVO.complete)
                        .userId(message.getUserId())
                        // 积分模块的外部单号就是活动充值模块传入的orderId;
                        .orderId(message.getOutBusinessNo())
                        .build();
                raffleActivityRepository.updateTradeOrder(rechangeTradeResult);
                break;
            default:
                break;
        }
    }
}
